import { ref } from 'vue';
import { accountService } from '@/services/security/LoginAccount';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Ref } from '@vue/reactivity';

export interface UseUpgradePhone {
  phone: Ref<string | null>;
  password: Ref<string | null>;
  visible: Ref<boolean>;
  handleClosePhone: () => void;
  confirmCancelPhone: (done: () => void) => void;
  handleUpdatePhone: () => Promise<void>;
  handleDeletePhone: () => Promise<void>;
}

export const useUpgradePhone = (refresh: () => void): UseUpgradePhone => {
  const phone = ref(null as string | null);
  const password = ref(null as string | null);
  const visible = ref(false);

  const handleClosePhone = () => {
    password.value = null;
    phone.value = null;
    visible.value = false;
    refresh();
  };

  const confirmCancelPhone = (done: () => void) => {
    ElMessageBox.confirm('确认关闭？')
      .then(() => {
        password.value = null;
        phone.value = null;
        done();
      })
      .catch(() => {})
      .finally(refresh);
  };

  const handleUpdatePhone = async () => {
    try {
      await accountService.upgradePhone(password.value as string, phone.value as string);
    } catch (e) {
      ElMessage.error((e as Error).message);
    } finally {
      handleClosePhone();
    }
  };

  const handleDeletePhone = async () => {
    try {
      await accountService.deletePhone();
    } catch (e) {
      ElMessage.error((e as Error).message);
    } finally {
      refresh();
    }
  };

  return {
    phone,
    password,
    visible,
    handleClosePhone,
    confirmCancelPhone,
    handleUpdatePhone,
    handleDeletePhone,
  };
};
